package com.czk.factory.support;

import com.czk.exception.BeansException;
import com.czk.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @Author:ChenZhangKun
 * @Date: 2023/2/19 10:23
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();


    @Override
    protected Object createBean(String name, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, name, args);
        } catch (Exception e) {
            throw new BeansException(" Instantiation of bean failed", e);
        }
        // 注册到单例池
        registerSingleton(name, bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String name, Object[] args) {
        Constructor constructorToUseConstructor = null;
        Class<?> beanClass = beanDefinition.getClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor<?> ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUseConstructor = ctor;
            }
        }
        return instantiationStrategy.instantiate(beanDefinition, name, constructorToUseConstructor, args);
    }
}
